import 'package:flutter/cupertino.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';

import '../../resources/kq_theme_colors.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import '../popMenu/kq_popup_menu.dart';
import 'kq_head_button.dart';

/// @author 高裕
/// 弹出菜单按钮，封装了KqPopupMenuButton
class KqPopMenuButton extends StatefulWidget {
  const KqPopMenuButton({
    super.key,
    required this.child,
    required this.menuData,
    required this.width,
    required this.height,
    this.onSelected,
    this.menuOffset,
    this.position,
    this.shape,
    this.elevation,
    this.bgColor,
  });

  final double width;

  final double height;

  /// 图标或文字
  final Widget child;

  /// 弹出菜单Builder
  final List<KqPopMenuItemData> menuData;

  /// 弹出菜单选中事件
  final OnMenuSelectListener? onSelected;

  /// 弹出气泡的偏移
  final Offset Function(double menuWidth, double menuHeight)? menuOffset;

  /// 方位
  final KqPopupMenuPosition? position;

  /// shape
  final ShapeBorder? shape;

  /// 海拔
  final double? elevation;

  /// 底层颜色
  final Color? bgColor;

  @override
  State<StatefulWidget> createState() => _KqPopMenuButtonState();
}

class _KqPopMenuButtonState extends State<KqPopMenuButton> {
  @override
  Widget build(BuildContext context) {
    double menuWidth = getItemWidth(widget.menuData);
    double menuHeight = getHeight(widget.menuData);
    return SizedBox(
      width: widget.width,
      height: widget.height,
      child: KqPopupMenuButton(
        padding: EdgeInsets.zero,
        menuVerticalPadding: 0,
        splashRadius: menuHeight / 2,
        color: widget.bgColor ?? const Color(0xffEAEEF2),
        offset: widget.menuOffset != null
            ? widget.menuOffset!.call(menuWidth, menuHeight) +
                getOffSet(menuWidth, menuHeight)
            : getOffSet(menuWidth, menuHeight),
        elevation: widget.elevation ?? 6,
        position: widget.position ?? KqPopupMenuPosition.left,
        shape: widget.shape ??
            RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(4.r)),
            ),
        itemBuilder: (context) {
          return _buildItems(widget.menuData, menuWidth);
        },
        onSelected: (entity) {
          if (widget.onSelected != null) {
            widget.onSelected!(entity.position ?? -1, entity);
          }
        },
        child: widget.child,
      ),
    );
  }

  List<KqPopupMenuItem<KqPopMenuItemData>> _buildItems(
      List<KqPopMenuItemData> data, double menuWidth) {
    int i = 0;
    for (KqPopMenuItemData e in data) {
      e.position = i;
      i++;
    }
    List<KqPopupMenuItem<KqPopMenuItemData>> list = [];
    for (int j = 0; j < data.length; j++) {
      KqPopMenuItemData item = data[j];
      list.add(KqPopupMenuItem<KqPopMenuItemData>(
        value: item,
        padding: EdgeInsets.zero,
        height: j < data.length - 1 ? 65.r : 64.r,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              height: 64.r,
              width: menuWidth,
              color: item.bgColor ?? const Color(0xffEAEEF2),
              child: Padding(
                padding: EdgeInsets.only(
                    left: item.imagePosition == KqPopMenuImagePosition.right
                        ? 16.r
                        : 32.r,
                    right: item.imagePosition == KqPopMenuImagePosition.right
                        ? 32.r
                        : 16.r),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Visibility(
                      visible: item.imageUrl != null &&
                          item.imagePosition == KqPopMenuImagePosition.left,
                      child: Container(
                        margin: EdgeInsets.only(right: 9.r),
                        child: Align(
                          child: item.customImage ??
                              Image.asset(
                                item.imageUrl ?? "",
                                width: 32.r,
                                height: 32.r,
                                fit: BoxFit.cover,
                                colorBlendMode:
                                    item.autoIconColor ? BlendMode.srcIn : null,
                                color: item.autoIconColor
                                    ? (KqThemeManager.getButtonConfig()
                                                .headButtonMenuIconColor ??
                                            KqThemeColors.text26)
                                        .withOpacity(
                                            item.hasPermission ? 1.0 : 0.25)
                                    : null,
                              ),
                        ),
                      ),
                    ),
                    Text(
                      item.title,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: item.fontSize ??
                              KqThemeManager.getButtonConfig()
                                  .headButtonMenuFontSize ??
                              24.sp,
                          color: (item.textColor ??
                                  KqThemeManager.getButtonConfig()
                                      .headButtonMenuTextColor ??
                                  KqThemeColors.text26)
                              .withOpacity(item.hasPermission ? 1.0 : 0.25)),
                    ),
                    Visibility(
                      visible: item.imageUrl != null &&
                          item.imagePosition == KqPopMenuImagePosition.right,
                      child: Container(
                        margin: EdgeInsets.only(left: 9.r),
                        child: item.customImage ??
                            Image.asset(
                              item.imageUrl ?? "",
                              width: 32.r,
                              height: 32.r,
                              fit: BoxFit.fill,
                              colorBlendMode:
                                  item.autoIconColor ? BlendMode.srcIn : null,
                              color: item.autoIconColor
                                  ? (KqThemeManager.getButtonConfig()
                                              .headButtonMenuIconColor ??
                                          KqThemeColors.text26)
                                      .withOpacity(
                                          item.hasPermission ? 1.0 : 0.25)
                                  : null,
                            ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Visibility(
                visible: j < data.length - 1,
                child: KqDivider(
                  height: 1.r,
                  color: const Color(0xFFD6DAE0),
                ))
          ],
        ),
      ));
    }
    return list;
  }

  double getHeight(List<KqPopMenuItemData> data) {
    return data.length * 64.r + ((data.length - 1) * 1.r);
  }

  Offset getOffSet(double menuWidth, double menuHeight) {
    KqPopupMenuPosition position = widget.position ?? KqPopupMenuPosition.left;
    switch (position) {
      case KqPopupMenuPosition.over:
        return Offset(0, -menuHeight - 10.r);
      case KqPopupMenuPosition.under:
        return Offset(0, 10.r);
      case KqPopupMenuPosition.left:
        return Offset(-menuWidth - 10.r, widget.height - menuHeight);
      case KqPopupMenuPosition.right:
        return Offset(10.r, widget.height - menuHeight);
    }
  }

  /// 获取项的宽度
  double getItemWidth(List<KqPopMenuItemData> data) {
    double maxTextWidth = 0;
    for (KqPopMenuItemData item in data) {
      double textWidth = paintHeightWithTextStyle(item) + 1.r; // 留点余裕
      if (textWidth > maxTextWidth) {
        maxTextWidth = textWidth;
      }
    }
    double width = 0;
    if (data.isNotEmpty && data[0].imageUrl != null) {
      width = maxTextWidth + 89.r;
      width = width < 213.r ? 213.r : width;
    } else {
      width = maxTextWidth + 32.r;
      width = width < 156.r ? 156.r : width;
    }
    return width;
  }

  /// 计算内容宽度
  double paintHeightWithTextStyle(
    KqPopMenuItemData item,
  ) {
    final TextPainter textPainter = TextPainter(
        text: TextSpan(
            text: item.title,
            style: TextStyle(
                fontSize: item.fontSize ??
                    KqThemeManager.getButtonConfig().headButtonMenuFontSize ??
                    24.sp)),
        maxLines: 1,
        textDirection: TextDirection.ltr)
      ..layout(minWidth: 0, maxWidth: 200.r);
    return textPainter.size.width;
  }
}
